<template>
    <a-tree-select
        v-model="myparentId"
        :disabled="optFlag==3"
        show-search
        treeNodeFilterProp="title"
        style="width: 100%"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
        :allow-clear="allowClear"
        :treeDefaultExpandedKeys='treeDefaultExpandedKeys'
        :tree-data="treeData"
        @change="selectTree"
        searchPlaceholder="关键字搜索"
        :placeholder="placeholder"
        autocomplete="off"
        :multiple="multiple"
        @focus="inputFocus"
    >
    </a-tree-select>
</template>

<script>
import { independentData, cacheIndependent, cacheUnit, menuByCondition , worksTree , unitTree} from "@/api/component";
export default {
  data() {
    return {
        treeDefaultExpandedKeys: ['-1'],//默认展开无上级单位
        initData:[],
        treeData:[],
        myparentId:'undefined',
        focusRequest: false,//点击下拉树请求数据 是否已请求标识
        myId:'',
    };
  },
  props: {
    filterFlag: { //查询树数据时是否排除编辑id本身节点
        type: Boolean,
        default: false
    },
    placeholder:{//占位提示语
        type: String,
        default: '请选择'
    },
    multiple:{
        type: Boolean,//是否多选
        default: false
    },
    isThreeFalse: { //三权分立是否固定传false
      type: Boolean,
      default: false
    },
    allowClear:{
        type: Boolean,
        default: true
    },
    topSelect:{
        type: String,
        default: '无上级单位'
    },
    id:{
        type:String,
        default:''
    },
    requestFlag:{
        type: Number,
        default: 1
    },
    parentId:{
        // type: String,
        default: undefined,
    },
    optFlag:{
        type: Number,
        default: 1  // 1新增 2编辑 3查询
    },
    selectFunc: {
        type: Function,
        default: ()=>{}
    },
    focusTrigger: {
        type: Boolean,
        default: false
    }
  },
  mounted() {
    if(!this.focusTrigger){
        this.getCommon();
    }else{
        this.treeData.unshift({key:'',title:this.topSelect,id:'',parentId:'-1',name:this.topSelect});
    }
    this.myId = this.id;
  },
  methods: {
    //树数据选择
    selectTree(value){
        this.myparentId = value;
        this.$emit('selectFunc',value);
    },
    inputFocus() {
        if(!this.focusRequest&&this.focusTrigger){
            this.getCommon();
            this.focusRequest=true;
        }
    },
    //获取独立结构树选择框数据
    getCommon() {
        this.myparentId = this.parentId;
        if(this.requestFlag===1){//独立机构
          this.getIndependent();
          return
        }
        if(this.requestFlag===2){//工作组
          this.worksTree();
          return
        }
        if(this.requestFlag===3){//部门
          this.unitTree();
          return
        }
        if(this.requestFlag===4){//菜单
          this.getMenuData();
          return
        }
        if(this.requestFlag===5){//从缓存中获取独立机构  和requestFlay为1时接口数据一致
          this.cacheIndependent();
          return
        }
        if(this.requestFlag===6){//从缓存中获取独立机构下所有部门树 和requestFlay为3时接口数据一致
          this.cacheUnit();
          return
        }
    },
    //获取独立机构树接口数据
    getIndependent(){
        this.loading = true;
        independentData()
        .then((res) => {
            if(this.topSelect.indexOf('=请选择')>-1){
                this.setUnitData(res.data.data,'id','parentId','children');
            }else{
                this.setTreeData(res.data.data,'id','parentId','children');
            }
        })
        .catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    //从缓存中获取所有单位(独立机构)
    cacheIndependent(){
        this.loading = true;
        cacheIndependent()
        .then((res) => {
            if(this.topSelect.indexOf('=请选择')>-1){
                this.setUnitData(res.data,'id','parentId','children');
            }else{
                this.setTreeData(res.data,'id','parentId','children');
            }
        })
        .catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    //获取菜单列表树接口数据
    getMenuData(){
        this.loading = true;
        menuByCondition({hasSeparate:this.isThreeFalse?false:undefined,hasButton:true,rootId:JSON.parse(localStorage.getItem('userInfo')).rootId})
        .then((res) => {
            this.setTreeData(res.data.data,'id','parentId','children');
        })
        .catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    worksTree(){
        this.loading = true;
        worksTree()
        .then((res) => {
            this.setTreeData(res.data.data,'id','parentId','children');
        })
        .catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    unitTree(){
        this.loading = true;
        unitTree()
        .then((res) => {
             if(this.topSelect.indexOf('=请选择')>-1){
                if(this.filterFlag){
                    this.setUnitFilter(res.data.data,'id','parentId','children');
                }else{
                    this.setUnitData(res.data.data,'id','parentId','children');
                }
            }else{
                this.setTreeData(res.data.data,'id','parentId','children');
            }
        })
        .catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    //从缓存中获取独立机构下所有部门树
    cacheUnit(){
        this.loading = true;
        cacheUnit()
        .then((res) => {
             if(this.topSelect.indexOf('=请选择')>-1){
                this.setUnitData(res.data.data,'id','parentId','children');
            }else{
                this.setTreeData(res.data.data,'id','parentId','children');
            }
        })
        .catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        })
        .finally(() => {
            this.loading = false;
        });
    },
    //处理树数据 编辑情况下需要过滤机构本身
    setTreeData(data,idFieldName,pidFieldName, childname){
        let $this = this,
            topPid = '-1';
        this.initData = data;
        let cloneData = JSON.parse(JSON.stringify(data))// 对源数据深度克隆
        if($this.topSelect){
            cloneData.push({id:'-1',parentId:'-2',name:$this.topSelect});
            topPid = '-2';
        }else {
            topPid = '-1'
        }
        this.treeData = cloneData.filter((father)=>{//循环所有项
            father.key = father.value = father.id;
            father.title = father.name;
            let branchArr = cloneData.filter((child)=>{
                return father[idFieldName] == child[pidFieldName]&&($this.optFlag!=2||($this.optFlag==2&&child[idFieldName]!=$this.myId))//返回每一项的子级数组
            });
            if(branchArr.length>0){
                father[childname] = branchArr;//如果存在子级，则给父级添加一个children属性，并赋值
            }
            return father[pidFieldName]===topPid&&($this.optFlag!=2||($this.optFlag==2&&father[idFieldName]!=$this.myId))//返回第一层
        });
    },
    //处理所属单位数据
    setUnitData(data,idFieldName,pidFieldName, childname){
        let $this = this;
        this.initData = data;
        let cloneData = JSON.parse(JSON.stringify(data))// 对源数据深度克隆
        cloneData.unshift({id:'',parentId:'-1',name:$this.topSelect});
        this.treeData = cloneData.filter((father)=>{//循环所有项
            father.key = father.value = father.id;
            father.title = father.name;
            let branchArr = cloneData.filter((child)=>{
                return father[idFieldName] == child[pidFieldName]//返回每一项的子级数组
            });
            if(branchArr.length>0){
                father[childname] = branchArr;//如果存在子级，则给父级添加一个children属性，并赋值
            }
            return father[pidFieldName]==-1//返回第一层
        });
    },
    //处理树数据 编辑情况下需要过滤机构本身
    setUnitFilter(data,idFieldName,pidFieldName, childname){
        let $this = this;
        this.initData = data;
        let cloneData = JSON.parse(JSON.stringify(data))// 对源数据深度克隆
        cloneData.unshift({id:'',parentId:'-1',name:$this.topSelect});
        this.treeData = cloneData.filter((father)=>{//循环所有项
            father.key = father.value = father.id;
            father.title = father.name;
            let branchArr = cloneData.filter((child)=>{
                return father[idFieldName] == child[pidFieldName]&&($this.optFlag!=2||($this.optFlag==2&&child[idFieldName]!=$this.myId))//返回每一项的子级数组
            });
            if(branchArr.length>0){
                father[childname] = branchArr;//如果存在子级，则给父级添加一个children属性，并赋值
            }
            return father[pidFieldName]==-1&&($this.optFlag!=2||($this.optFlag==2&&father[idFieldName]!=$this.myId))//返回第一层
        });
    },
  },
  computed: {},
  watch: {
      parentId(n){
          this.myparentId = n;
      },
      id(n){
        this.myId = n;
        if(this.requestFlag===4){//菜单
            this.getMenuData();
            return
        }
        if(this.requestFlag===1){//独立机构
            this.getIndependent();
            return
        }
      }
  }
};
</script>

<style lang="stylus" scoped>
@import '~stylus/mixin.styl';
.search-tree 
    overflow-y auto
    pos(115px, 24px, 24px, 24px, 1, 0)
</style>